<template>
  <div :key="timestrim">
    <el-button size="small" type="primary" @click="init">选择图片</el-button>
    <el-dialog
      title="图片库"
      width="72%"
      :visible.sync="dialogVisible"
      :append-to-body="true">
     <el-row :gutter="4" class="toprow">
        <el-col :span="5" >
          <div  >
            <el-menu >
              <el-menu-item active="true" @click="changeImg(-1)">全部图片</el-menu-item>
              <el-menu-item v-for="(group, index) in groups" :key="index" @click="changeImg(group.group_id)"  @mouseover.native="group.is_show_btn=true" @mouseout.native="group.is_show_btn=false">
                <el-row :gutter="23">
                  <el-col :span="16">{{group.group_name}}</el-col>
                  <el-col :span="8" v-show="group.is_show_btn">
                    <el-button class="my-edit-btn" icon="el-icon-edit" type="text" size="mini" @click="editGroup(group,$event,index)"></el-button>
                    <el-button class="my-del-btn" icon="el-icon-delete" type="text"  size="mini" @click="deleteGroup(group.group_id,$event,index)"></el-button>
                  </el-col>
                </el-row>
              </el-menu-item>
              <el-menu-item @click="editGroup(null,null,0)" class="el-icon-plus" style="width:100%">新增分组
                </el-menu-item>
            </el-menu>
          </div>
        </el-col>
        <el-col :span="19">
          <el-row class="op-btn">
              <el-button @click="deleteImgs" type="danger" icon="el-icon-delete" size="small">删除图片</el-button>
            </el-row>
          <div class="photos" style="height:430px;" @scroll="autoPages($event)">
            <el-row class="top10">
              <div class="image-lib">
                <div class="up-block">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploade_api"
                    :show-file-list="false"
                    name="iFile"
                    multiple
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <i class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </div>
                <div class="block" v-for="(img,index) in imgs" :key="index">
                  <el-checkbox :indeterminate="false"  @change="setCallBackData(img)" :label="img.file_id" class="file-name-checkbox">
                  <el-image
                    class="image-select"
                    :src="img.file_path"
                    :fit="'cover'"></el-image><br>
                    <span class="file-name">{{img.file_name}}</span></el-checkbox>
                </div>
              </div>
            </el-row>
          </div>
          <el-row >
            <el-col :offset="18">
              <el-button type="primary" size="small"  @click="selectImg"><i class="el-icon-check"></i> 确定</el-button>
              <el-button type="" icon="el-icon-delete" size="small" @click="dialogVisible = false">取消</el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog
      title="请输入分组名称"
      :visible.sync="addGroupVisible"
      width="30%">
      <el-input v-model="group_name"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addGroupVisible = false">取 消</el-button>
        <el-button type="primary" @click="groupEditSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { cookieGet } from '@/common/cookie'
export default {
  props: ['menu', 'photo'],
  data () {
    return {
      dialogVisible: false,
      showBtnGroup:false,
      addGroupVisible: false,
      group_name:'',
      imgs: [],
      newimg_flag:false,
      uploade_api:'',
      groups:[],
      that_group:-1,
      that_index:-1,
      back_data:[],
      timestrim:1,
      query_page:2,
    }
  },
  created: function () {
    this.getToken()
  },
  methods: {
    init(){
      this.timestrim = new Date().getTime()
      this.dialogVisible = true
      this.back_data=[]
      this.getFileList()
    },
    autoPages(e) {
      var scrollTop = e.target.scrollTop;
      var windowHeight = e.target.clientHeight;
      var scrollHeight = e.target.scrollHeight;
      if(scrollTop+windowHeight>=scrollHeight){
        this.$axios.get(`/api/upload.library/filelist?group_id=${this.that_group}&page=${this.query_page}`).then(res => {
          console.log(res.file_list.length)
          if (res.file_list.data.length > 0) {
            res.file_list.data.forEach(item => {
              this.imgs.push(item)
            })
            ++this.query_page
          } else {
            this.$message({
              type: 'info',
              message: '没有更多图片了。'
            });
          }
        }).catch(() => {})
      }
    },
    groupEditSubmit() {
      var option = 'post'
      var url = ''
      var data = {}
      if (this.that_group != -1) {//编辑
          url = '/api/upload.library/editGroup'
          option = 'put'
          data = {'group_id':this.that_group, 'group_name':this.group_name}
      } else {//新增
          url = '/api/upload.library/addGroup'
          option = 'post'
          data = {'group_name':this.group_name}
      }
      this.$axios[option](url, data).then(res => {
        this.$message({
          message: this.$t('prompt.success'),
          type: 'success',
          duration: 500,
        })
        if (option === 'post') {
          this.groups.push({
            'group_id':res.group_id,
            'group_name':res.group_name
          })
        } else {
          this.groups[this.that_index].group_name = this.group_name
          this.that_index = -1
        }
        this.addGroupVisible = false
      }).catch(() => {})
      this.that_group = -1;
    } ,
    editGroup(group,event,index){
      if (group) {//编辑
        this.that_group = group.group_id
        this.group_name = group.group_name
        this.that_index = index
        event.stopPropagation()
      }
      this.addGroupVisible = true
    },
    deleteGroup(group_id,event,index){
      this.that_group = group_id
      this.$confirm('确定要删除该分类么?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios['delete'](`/api/upload.library/deleteGroup?group_id=${group_id}`, {}).then(res => {
          this.groups.splice(index,1)//删除当前数据对象
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
          })
        }).catch(() => {})
        this.groups.splice(index,1)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
      event.stopPropagation()
    },
    getFileList(group_id=-1) {
      this.$axios.get(`/api/upload.library/filelist?group_id=${group_id}`).then(res => {
        this.imgs = res.file_list.data
        var temp_group = res.group_list;
        temp_group.forEach(element => {
          element.is_show_btn = false//手动增加一个字段
        });
        this.groups = temp_group
      }).catch(() => {})
    },
    getToken() {
      var token = cookieGet("token")
      this.uploade_api = `${process.env.VUE_APP_API}/api/upload/image?group_id=${this.that_group}&&token=${token}`
    },
    changeImg:function(id) {
      var token = cookieGet("token")
      this.uploade_api = `${process.env.VUE_APP_API}/api/upload/image?group_id=${id}&&token=${token}`
      this.getFileList(id)
    },
    setCallBackData(obj) {
      var temp_data = this.back_data
      var is_delete=false
      temp_data.forEach(function(item, index){
        if (item.file_id === obj.file_id) {
          is_delete = true
          temp_data.splice(index,1)
        }
      })
      if (!is_delete) {
        this.back_data.push({
          file_id:obj.file_id,
          file_path:obj.file_path
        })
      } else {
        this.back_data = temp_data
      }
    },
    selectImg () {
      this.$emit('getSelectFileInfo', this.back_data)
      this.dialogVisible = false
    },
    deleteImgs() {
      if(this.back_data == []) {
        return this.$message.error('你没有选中任何图片!');
      }
      var file_ids = []
      this.back_data.forEach(item=>{
        file_ids.push(item.file_id)
      })
      
      var del_data = {'fileIds':file_ids}
      this.$confirm('确定要删除选中的图片吗?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios['post'](`/api/upload.library/deleteFiles`, del_data).then(res => {
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
          })
          this.init()
        }).catch(() => {})
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    handleAvatarSuccess (res) {
      var file = res.data
      this.$message({
        showClose: true,
        message: '上传成功。',
        type: 'success'
      })
      this.imgs.unshift({
        file_path:file.file_path,
        file_name:file.file_name,
        file_id:file.file_id
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('请上传图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('文件大小不能超过2MB!');
      }
      return isJPG && isLt2M;
    },
  }
}
</script>
<style>
.photos{
  margin: 10px;
  overflow-y: auto;
  height: 430px;
}
.op-btn{
   margin-left: 10px;
}
.toprow{
  margin-top:-20px;
}
.top10{
  margin-top: 10px;
}
.file-name-checkbox{
  width: 130px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.image-select{
  width: 140px; 
  height: 130px;
  margin-left:-110px;
}
.block{
    margin: 10px;
    text-align: center;
    border: 1px solid #eff2f6;
    display: inline-block;
    width: 155px;
    height: 155px;
    box-sizing: border-box;
    vertical-align: top;
    cursor:pointer;
}
.up-block{
  margin: 10px;
    text-align: center;
    display: inline-block;
    width: 155px;
    height: 155px;
    box-sizing: border-box;
    vertical-align: top;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 155px;
    height: 155px;
    line-height: 155px;
    text-align: center;
  }
  .avatar {
    width: 155px;
    height: 155px;
    display: block;
  }
</style>
